$(function(){
	var global_info = {
			'page': $_GET['page'] ? $_GET['page'] : undefined,//页码
			'pageSize' : $_GET['pageSize'] ? $_GET['pageSize'] : undefined, //页数
			'cond':[] //查询条件
					
		}
		remove =[];
		//管理员列表
		listGroup();
		function listGroup(pageInfo)
		{
			if (pageInfo !== undefined) {
				global_info.page = pageInfo.page;
				global_info.pageSize = pageInfo.pageSize;
			}
			$('#grouplist').find('tr').remove();
			$.get('get-groups',global_info,function(data,status){
				if(status ==='success'){
					if(data.Ack ==='Success'){
						var G = data.Body.list;
						if(G && G.length){
							for(var i in G){
								$('<tr><td class="text-center"><input type="checkbox"  class="ids" data-name="'+G[i].name+'"></td>'
								+'<td class="text-center" name="name" data-name="'+G[i].name+'">'+G[i].description+'</td>'
								+'<td class="text-center"><a href="javascript:void(0)" class="group_edit fa fa-pencil-square-o fa-2x" title="编辑"></a>&nbsp;&nbsp;<a href="javascript:void(0)" class="group_assign fa fa-cogs fa-2x" title="分配权限"></a></td>'
								+'</tr>').appendTo('#grouplist');
				                var pageInfo = data.Body.page;
				                if (typeof pageInfo !== 'undefined'){
				                	refreshPaginationNavBar($('.paginationNavBar'), pageInfo.page, pageInfo.pageSize, data.Body.count, listGroup);
				                }
							}
						}else {
							$('<tr><td colspan="6" class="text-center">没有数据</td></tr>').appendTo('#grouplist');
							refreshPaginationNavBar($('.paginationNavBar'), 1, 10, 1, listGroup);
						}
					} else {
						$('<tr><td colspan="6" class="text-center">没有数据</td></tr>').appendTo('#grouplist');
						refreshPaginationNavBar($('.paginationNavBar'), 1, 10, 1, listGroup);
					}
				} else{
					alertTips('error','网络错误',1500);
				}
			});
		}
	
	/**
	 * @desc 新增分组
	 */
	$('#add').on('click',function(){
		//检查是否有新增功能
		$.get('check-add-group',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
			$('#groupname').val('');
			$('#group_save').attr('data-group', '');
			$('#groupname').attr('class','form-control valid');
			$('#groupname-error').hide();
			$('#myModal').modal('show');
		})
		
	});
	
	
	/**
	 * @desc 编辑
	 */
	$('#grouplist').on('click','.group_edit',function(){
		var tr = $(this).closest('tr').find('[name="name"]');
		//检查是否有编辑功能
		$.get('check-edit-group',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
			$('#groupname').attr('class','form-control valid');
			$('#groupname-error').hide();
			
			var group = tr.attr('data-name');
			var name = tr.text();
			$('#group_save').attr('data-group',group);
			$('#groupname').val(name);
			$('#myModal').modal('show');
		})
		
	});
	
	
	/**
	 * @desc 新增权限分组
	 * @author liaojianwen
	 * @date 2017-01-07
	 */
	$('#group_save').on('click',function(){
		var group = $(this).attr('data-group');
		validateInfo(group);
	});	
		
	/**
	 * @desc 验证数据
	 */
	function validateInfo(group)
	{
		$('#groupinfo').validate({
			rules : {
				groupname : {
					required : true,
					remote: 'check-group?group='+group,
				},

			},
			messages : {
				groupname : {
					required : "请输入分组名",
					minlength : "分组名称必需由两个字母组成",
					remote : "分组名称已占用",
				},
			},
			submitHandler: function(form) { 
				saveGroup();
			} 
		});
	}
	
	/**
	 * @desc 保存分组
	 */
	function saveGroup()
	{
		var info = {
				'groupname' : $('#groupname').val(),
				'group': $('#group_save').attr('data-group'),
			};
		$.get('save-group', info, function(data, status) {
			if (status == 'success' ){
				if(data.Ack == 'Success') {
					alertTips('success','保存成功');
					window.location.reload();
				}else{
					alertTips('error','保存失败！');
					return false;
				}

			}
		});
		
	}
	
	$('#reset_info').on('click',function(){
		$('#groupname-error').hide();
		$('#groupname').attr('class','form-control');
	})
	
	//分配
	$('#grouplist').on('click','.group_assign',function(){
		var group = $(this).closest('tr').find('[name="name"]').attr('data-name');
		$.get('check-assign-group',function(data){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
			$('#saveAssign').attr('data-group',group);
			var ii = layer.load();
			$('#groupBody table').remove();
			$.get('list-auth',{'group': group},function(data,status){
				layer.close(ii);
				if(status==='success' && data.Ack ==='Success'){
					var A = data.Body.auth;
					var G = data.Body.group;
					var template = '<table><tr><td><select multiple="multiple" class="authSelect" id="leftSelect" style="height:300px;">';
					if(A){
						for(var i in A){
							template += '<optgroup label="' +i+ '">';
							for(var k in A[i]){
								template += '<option class="leftOption" data-auth="' + A[i][k].name + '">' + A[i][k].description + '</option>';
							}
						}
						template += '</select></td>';
						template += '<td><div style="margin-bottom: 10px;"><i class="fa fa-angle-double-right  btn btn-info" ></i></div><div><i class="fa fa-angle-double-left  btn btn-info"></i></div></td>';
						template += '<td><select multiple="multiple" class="authSelect" id="rightSelect" style="height:300px;">';
						// 已有权限列表
						$.each(G, function(index, item){
							template += '<optgroup label="' +index+ '">';
							for(var j in item){
								template += '<option class="rightOption" data-auth="' + item[j].name + '">' + item[j].description + '</option>';
							}
						});
						template += '</select></td>';
						template += '</tr></table>';
						$('#groupBody').append(template);
						cancelPermission();
						choosePermission();
//						savePermission();
						$('#permissionAssign').modal('show');
					} else {
						return false;
					}
					//
				} else {
					return false;
				}
			});
			$('#groupbox').show();
		});
		
	})
	
		
	//选择权限
	var choosePermission = function(){
		$('.leftOption').on('click',function() {
			var self = $(this),
				existPermission = $('.rightOption'),
				rightSelect = $('#rightSelect'),
				template = '',
				flag = false;
	
			$.each(existPermission, function(index, permission) {
				var permission = $(permission);
				if (permission.data('auth') == self.data('auth')) {
					flag = true;
					return false;
				}
			});
			if (!flag) {
				var key = self.data('auth');
				if ($.inArray(key, remove) >= 0) {
					remove.splice($.inArray(key, remove), 1);
				}
				var label = self.closest('optgroup').attr('label');
				var _flag = false;
				$('#rightSelect optgroup').each(function(iindex, element){
					
					if(label == $(element).attr('label')){
						template += '<option class="rightOption" data-auth="' + self.data('auth') + '">' + self.text() + '</option>';
						$(this).append(template);
						_flag = true;
					}
					
				})
				if(!_flag){
					template += '<optgroup label="'+label+'">'
					template += '<option class="rightOption" data-auth="' + self.data('auth') + '">' + self.text() + '</option>';
					template += '</optgroup>';
					rightSelect.append(template);
				}
//				template += '<option class="rightOption" data-auth="' + self.data('auth') + '">' + self.text() + '</option>';
//				rightSelect.append(template);
			}
		});
	}
	//取消权限
	var cancelPermission = function() {
		$('#rightSelect').on('click', '.rightOption', function() {
			var self = $(this),
				leftSelect = $('#leftSelect'),
				key = self.data('auth'),
				express = 'option[data-auth="' + key + '"]',
				leftOption = leftSelect.find(express);
			self.remove();
			if ($.inArray(key, remove) >= 0) {
				return true;
			}
			remove.push(key);
		});
	}
	
	// 保存按钮
	var savePermission = function() {
		$('#saveAssign').on('click', function() {
			var rightOption = $('.rightOption'),
				group = $('#authDiv').data('group'),
				postData = [];
			$.each(rightOption, function(index, item) {
				var item = $(item),
					value = item.data('auth');
				postData.push(value);
			});
			var _group_name = $('#saveAssign').attr('data-group'); 
			$.get('save-auth',{'auth':postData, 'remove': remove,'group': _group_name},function(data,status){
				if(status ==='success' && data.Ack ==='Success'){
					alertTips('success','保存成功');
				    setTimeout(function () {
				    	$('#permissionAssign').modal('hide');
				     }, 1500);
					
					return false;
				} else {
					alertTips('error','保存失败');
					return false;
				}
			})
		});
	}
	savePermission();
	
	//删除
	$('#delete').on('click',function(){
		//检查是否有删除功能
		$.get('check-del-group',function(data,status){
			if(data.Error =='User authentication fails'){
				alertTips('error', '你没有操作权限，如要操作，请向管理员申请');
				return;
			}
		
		var _all_ids='';
		$('.ids').each(function(i){
			if($(this).prop('checked')){
				_all_ids += $(this).attr('data-name') + ',';
			}
		})
		_all_ids = _all_ids.substr(0,_all_ids.length -1);
		if (_all_ids.length === 0) {
			alertTips('warning','请勾选复选框！');
			return false;
		}
		if(confirm("确定要删除分组？")){
			$.get('del-group',{'names':_all_ids},function(data,status){
				if(status ==='success' && data.Ack ==='Success'){
					alertTips('success','删除成功');
					setTimeout(function(){ 
						listGroup();
					},1500);
				}else {
					alertTips('error','删除失败，请重新再试');
				}
			});
		 }
		})
	});
	
	$('#search_list').on('click',function(){
		var name = $('#groupName').val();
		global_info.cond = {
			'name':name
		}
		listGroup();
		
	})
})